package com.sciai.Service.impl;

import cn.com.sciai.aix.common.http.SciaiHttpResponseEntity;
import cn.com.sciai.aix.common.http.SciaiHttpResponseEntityBuilder;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sciai.Service.SysLoginUserService;
import com.sciai.common.CommonConstant;
import com.sciai.entity.SysLoginUser;
import com.sciai.entity.req.LoginReq;
import com.sciai.entity.req.SysPersonUserReq;
import com.sciai.entity.vo.LoginUserInfo;
import com.sciai.mapper.SysLoginUserDao;
import com.sciai.utils.SM4;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


@Service("sysLoginUserService")
@Slf4j
public class SysLoginUserServiceImpl extends ServiceImpl<SysLoginUserDao, SysLoginUser> implements SysLoginUserService {

    @Value("${sm4.secretKey}")
    private String secretKey;
    @Override
    @Transactional
    public SciaiHttpResponseEntity personRegister(SysPersonUserReq req) {
        try {
            SysLoginUser loginUser = new SysLoginUser();
            Integer usernameCount = 0;
            Integer usernameCount2 = 0;

            //用户名校验重复
            loginUser.setUserName(req.getUserName());
            usernameCount = Math.toIntExact(this.baseMapper.selectCount(new LambdaQueryWrapper<SysLoginUser>()
                    .eq(SysLoginUser::getUserName, req.getUserName())));
            if (usernameCount > 0) {
                return SciaiHttpResponseEntityBuilder.builder().error("500","该用户已注册").build();
            }
//            //手机号校验重复
//            usernameCount2 = Math.toIntExact(this.baseMapper.selectCount(new LambdaQueryWrapper<SysLoginUser>()
//                        .eq(SysLoginUser::getPhone, req.getPhone())));
//            if (usernameCount2 > 0) {
//                return SciaiHttpResponseEntityBuilder.builder().error("500","该手机号已注册").build();
//            }

            loginUser.setPassword(SM4.encryptECB(req.getPassword(), secretKey));
            loginUser.setCreateTime(new Date());
            loginUser.setUserName(req.getUserName());
            loginUser.setCreateTime(new Date());
            loginUser.setUpdateTime(new Date());
//            loginUser.setPhone(req.getPhone());
            //保存数据
            this.baseMapper.insert(loginUser);
            return SciaiHttpResponseEntityBuilder.builder().ok("注册成功").build();
        }catch (Exception e){
            return SciaiHttpResponseEntityBuilder.builder().error("500",e.toString()).build();
        }
    }



    @Override
    public SciaiHttpResponseEntity login(LoginReq req) {
        try {

            String userName = req.getUserName();

            //1、去数据库查询 SELECT * FROM ums_member WHERE username = ? OR mobile = ?
            SysLoginUser loginUser = this.baseMapper.selectOne(new LambdaQueryWrapper<SysLoginUser>()
                    .eq(SysLoginUser::getUserName, userName).or().eq(SysLoginUser::getPhone, userName)
                    .eq(SysLoginUser::getDeleted, CommonConstant.SysLoginUserActive.Active));
            if (loginUser == null) {
                return SciaiHttpResponseEntityBuilder.builder().error("500", "该用户不存在！").build();
            } else if(CommonConstant.SysLoginUserActive.Deleted == loginUser.getDeleted()) {
                return SciaiHttpResponseEntityBuilder.builder().error("500", "该用户已经失效！").build();
            } else {
                //获取到数据库里的password
                //进行密码匹配
                boolean equals = SM4.encryptECB(req.getPassword(), secretKey).equals(loginUser.getPassword());
                if (equals) {
                    //登录成功

                    LoginUserInfo userInfo = new LoginUserInfo();
                    userInfo.setUserName(loginUser.getUserName());
                    userInfo.setId(loginUser.getId());
                    userInfo.setPhone(loginUser.getPhone());
                    userInfo.setType(loginUser.getType());

                    StpUtil.login(userInfo.getId());
                    StpUtil.getSession().set(CommonConstant.SESSION_USER_KEY, userInfo);
                    userInfo.setSatoken(StpUtil.getTokenValue());

                    return SciaiHttpResponseEntityBuilder.builder().ok(userInfo).build();
                }else {
                    return SciaiHttpResponseEntityBuilder.builder().error("500", "密码错误").build();
                }
            }

        }catch (Exception e){
            return SciaiHttpResponseEntityBuilder.builder().error("500",e.toString()).build();
        }
    }
}